package com.example.nio.util;

import cn.hutool.json.XML;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class DataTransUtil {
    public String xmlToJSONObject(HttpServletRequest request){
        StringBuffer reqXmlData = new StringBuffer();
        try {
            InputStream inputStream = request.getInputStream();
            String s;
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            while ((s = in.readLine()) != null) {
                reqXmlData.append(s);
            }
            in.close();
            inputStream.close();
        } catch (IOException e) {
            System.out.println("流解析xml数据异常!");
            e.printStackTrace();
        }
        //判断请求数据是否为空
        if (reqXmlData.length() <= 0) {
            System.out.println("请求数据为空!");
        }
        //json类型数据
       return XML.toJSONObject(reqXmlData.toString()).toString();
    }

    public Document requestToXML(HttpServletRequest request){
        Document document = DocumentHelper.createDocument();
        Element root = DocumentHelper.createElement("root");
        document.add(root);
        try {
            InputStream inputStream = request.getInputStream();
            SAXReader reader = new SAXReader();
            Document document1 = reader.read(inputStream);
            List<Element> message = document1.getRootElement().elements();
            for (Element msg:message){
                root.add((Element) msg.clone());
            }
            System.out.println(document.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return document;
    }
}
